package com.kaka.service.serviceimpl;

import com.kaka.mapper.RoleMapper;
import com.kaka.mapper.RolePermissionMapper;
import com.kaka.mapper.UsersRoleMapper;
import com.kaka.pojo.Role;
import com.kaka.pojo.Role_Pid;
import com.kaka.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private UsersRoleMapper usersRoleMapper;

    @Override
    public List<Role> findAll() {
        return roleMapper.selectAll();
    }

    @Override
    public Role findById(int id) {
        return roleMapper.selectById(id);
    }

    @Override
    public int editRole(Role role) {
        return roleMapper.updatePermission(role);
    }

    @Override
    public List<Integer> findPermissionByRid(int rid) {
        return roleMapper.selectAllPermissionId(rid);
    }

    @Override
    public void permissionAdd(Integer rid, List<Integer> ids) {
        //先删除关联表中当前角色对应的所有权限
        int i = roleMapper.deletePermissionByRId(rid);
        //使用集合在权限管理表中添加数据
        int j = roleMapper.addPermissionByList(rid, ids);
    }

    @Override
    public void editPermission(Role_Pid rp) {
        //删除原本角色的权限
        int i = rolePermissionMapper.deleteByRid(rp.getRid());
        //批量添加新的权限
        int j = rolePermissionMapper.insertArr(rp.getRid(), rp.getIds());
    }

    @Override
    public int addRole(Role role) {
        return roleMapper.insetRole(role);
    }

    @Override
    @Transactional
    public int deleteRole(int rid) {
        int i = usersRoleMapper.deleteByRid(rid);
        int j = rolePermissionMapper.deleteByRid(rid);
        int k = roleMapper.deleteById(rid);
        return i + j + k;
    }

    @Override
    @Transactional
    public int deleteRoles(List<Integer> ids) {
        int i = usersRoleMapper.deleteByRids(ids);
        int j = rolePermissionMapper.deleteByRids(ids);
        int k = roleMapper.deleteByIds(ids);
        return i + j + k;
    }
}
